import pupper from 'puppeteer'
const url = `https://movie.douban.com/explore#!type=movie&sort=recommend&page_limit=20&page_start=0&tag=`
const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})
pupper.launch({
  args: ['--no--sandbox']
}).then(async browser => {
  const blank = await browser.newPage()
  console.log('crawler start now...')
  await blank.goto(url, {
    waitUntil: 'networkidle2'
  }).catch(err => {
    console.error(err)
  })
  await sleep(2000)

  blank.waitForSelector(".more")

  for (let i in 1) {
    await sleep(1000)
    await blank.click(".more")
  }

  const result = await blank.evaluate(() => {
    var $ = window.$
    var items = $(".list > a")
    const source = []

    items.each((k, v) => {
      let it = v instanceof jQuery ? v : $(v)
      let coverWp = it.find(".cover-wp")
      let id = coverWp.data("id")
      let $rate = it.find('strong')
      let rate = $rate.text()
      let title = $rate[0].previousSibling.textContent.trim()
      let thumb = coverWp.find('img').attr("src").replace('s_ratio', 'm_ratio')
      source.push({
        id,
        title,
        rate,
        thumb
      })
    })
    return Promise.resolve(source)
  })
  await blank.close()
  process.send({result})
  setTimeout(() => {
    process.exit(0)
  })
}).catch(err => {
  console.error(err)
})
